package com.juntuo.controller;

import com.juntuo.entity.User;
import com.juntuo.service.UserService;
import com.juntuo.shiro.ShiroUtil;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 登录
 */
@Controller
public class LoginController {

//    private static final Logger logger = Logger.getLogger(LoginController.class);
//
    @Autowired
    private UserService userService;
    /**
     * 登录首页
     * @return
     */
    @RequestMapping(value="", method= RequestMethod.GET)
    public String index(){
//        if(SecurityUtils.getSubject().isAuthenticated()){
//            return "redirect:/main";
//        }


        return "/login";
    }

    /**
     * 登录首页
     * @return
     */
    @RequestMapping(value="/login", method= RequestMethod.GET)
    public String loginGet(){
//        if(SecurityUtils.getSubject().isAuthenticated()){
//            return "redirect:/main";
//        }
        return "/login";
    }

    /**
     * @Description 用户登录 post提交
     * @param model
     * @param session
     * @param username
     * @param password
     * @param checkCode
     * @return
     */
    @RequestMapping(value="/login", method= RequestMethod.POST)
    public String loginPost(Model model, HttpSession session,
                            String username, String password, String checkCode) {
        if(StringUtils.isEmpty(username)
                || StringUtils.isEmpty(password)){
            model.addAttribute("message", "用户名和密码不能为空");
            return "login";
        }

        //验证码校验
        String checkCodeServer = (String) session.getAttribute("checkCode");
        if (null == checkCode || checkCodeServer == null
                || !checkCodeServer.equals(checkCode)) {
            model.addAttribute("message", "验证码输入错误!");
            session.removeAttribute("checkCode");
            return "login";
        }

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
//        UsernamePasswordToken token = new UsernamePasswordToken(username, StringUtil.encodeMD5(password));
        try {
            //登录
            subject.login(token);
            if(subject.isAuthenticated()){
                User userExample = new User();
                userExample.setUsername(username);
                User loginUser = userService.selectOne(userExample);
                session.setAttribute("user", loginUser);

                //每次登录次数加1
                /*String userId = loginUser.getId();
                userDao.update().inc("loginCount", 1).execute(userId);*/

                //登录日志
               /* int type = LogEnum.type.LOGIN.getCode();
                int module=  LogEnum.module.LOGIN.getCode();
                String content = username + "登录系统";
                logDao.save(type, module, content);*/
                return "redirect:/device/index";
            }else{
                token.clear();
            }
        }catch (LockedAccountException uae){
//            logger.error("对用户[" + username + "]进行登录验证..用户被禁用");
            uae.printStackTrace();
            model.addAttribute("message", "用户被禁用");
            return "login";
        }catch(Exception uae){
//            logger.error("对用户[" + username + "]进行登录验证..验证异常");
            uae.printStackTrace();
            model.addAttribute("message", "用户名或密码错误");
            return "login";
        }
        return "login";
    }
//
//    /**
//     * @Description: 未授权
//     */
//    @RequestMapping("/unauth")
//    public String unauth(Model model){
//        if(!SecurityUtils.getSubject().isAuthenticated()){
//            return "redirect:/login";
//        }
////        model.addAttribute("url", Page.MAIN_URL);
//        return "unauth";
//    }
//
    /**
     * @Description 用户注销
     * @param request
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        ShiroUtil.logout(request);
        return "redirect:/login";
    }

}
